package com.msb.strategy.util;

import com.msb.common.constart.CacheConstant;
import com.msb.common.constart.RabbitMQConstants;
import com.msb.common.constart.SmsConstant;
import com.msb.common.enums.ExceptionEnums;
import com.msb.common.exception.GraceException;
import com.msb.common.model.StandardReport;
import com.msb.common.model.StandardSubmit;
import com.msb.strategy.feign.BeaconCacheClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: lmf
 * @Create: 2025/3/13 11:28
 * @module 验证异常发送对应消息
 */
@Component
public class ErrorSendMessage {
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private BeaconCacheClient cacheClient;

    public void sendErrorMessage(StandardSubmit submit, ExceptionEnums exceptionEnums) {
        // 推送消息到es
        Integer isCallback = sendErrorMsgToEs(submit);
        // 是否需要推送消息给客户端
        if (SmsConstant.IS_CALLBACK_YES.equals(isCallback)) {
            sendErrorMessageToLog(submit, isCallback);
        }
        GraceException.display(exceptionEnums);
    }

    public void sendErrorMessage(StandardSubmit submit) {
        // 推送消息到es
        Integer isCallback = sendErrorMsgToEs(submit);
        // 是否需要推送消息给客户端
        if (SmsConstant.IS_CALLBACK_YES.equals(isCallback)) {
            sendErrorMessageToLog(submit, isCallback);
        }
    }

    /**
     * 发送错误消息到es
     */
    public Integer sendErrorMsgToEs(StandardSubmit submit) {
        submit.setReportState(SmsConstant.SEND_FAIL);

        // 发送日志到es
        rabbitTemplate.convertAndSend(RabbitMQConstants.SMS_LOG_ES, submit);
        // 查询客户是否需要推送消息
        return cacheClient.hGetInteger(CacheConstant.CLIENT_BUSINESS + submit.getApiKye(), "isCallback");
    }

    /**
     * 发送错误消息到客户端
     */
    public void sendErrorMessageToLog(StandardSubmit submit, Integer isCallback) {
        // 获取回调地址
        String callbackUrl = cacheClient.hGet(CacheConstant.CLIENT_BUSINESS + submit.getApiKye(),
                "callbackUrl");

        StandardReport standardReport = new StandardReport();
        BeanUtils.copyProperties(submit, standardReport);
        standardReport.setCallbackUrl(callbackUrl);
        standardReport.setIsCallback(isCallback);

        rabbitTemplate.convertAndSend(RabbitMQConstants.SMS_SEND_CLIENT, standardReport);
    }

}
